//
//  IGFindRadioPlayViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGFindRadioPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "IGFindRadioPlayTBVHeadView.h"
#import "IGFindRadioPlayTableViewCell.h"
#import "IGRadioPlayCommentTableViewCell.h"
#import "IGFindMainTBVModel.h"
#import "IGFindCommentView.h"
#import "IGFindCommentModel.h"
#import "IGLoginViewController.h"

@interface IGFindRadioPlayViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) IGFindRadioPlayTBVHeadView *headView;

@property (nonatomic, strong) NSDictionary *dataDic;
@property (nonatomic, strong) NSMutableArray *moreMovieArray;
@property (nonatomic, strong) IGCustomNavigationController *navc;
@property (nonatomic, strong) UIButton *returnButton;

@property (nonatomic, strong) IGFindCommentView *commentView;
@property (nonatomic, strong) NSMutableArray *commentArray;
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (nonatomic, assign) BOOL ss;

@end

@implementation IGFindRadioPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.automaticallyAdjustsScrollViewInsets = NO;
    _ss = YES;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 100;
    
    [_tableView registerNib:[UINib nibWithNibName:@"IGFindRadioPlayTableViewCell" bundle:nil] forCellReuseIdentifier:@"IGFindRadioPlayTableViewCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IGRadioPlayCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"IGRadioPlayCommentTableViewCell"];
    _tableView.autoresizesSubviews = NO;
   
    _headView = [[UINib nibWithNibName:@"IGFindRadioPlayTBVHeadView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    _tableView.backgroundColor = _headView.backgroundColor;
    
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleShrink];
    [MMProgressHUD showWithTitle:nil status:@"正在加载中"];
    
    // 数据请求
    _moreMovieArray = [NSMutableArray array];
    [self requestPlayDetailData];
    // 添加评论的View
    [self addCommmentView];
    _commentArray = [NSMutableArray array];
    [self requestCommentData];
    
    self.view.backgroundColor = _headView.backgroundColor;
   
    // 解决push后侧滑返回失效问题
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}

- (CGFloat)customHeight:(NSString *)content FontOfSize:(CGFloat)size width:(CGFloat)width
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:size],NSFontAttributeName, nil];
    CGRect textRect = [content boundingRectWithSize: CGSizeMake(width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    return textRect.size.height;
}

- (void)viewWillAppear:(BOOL)animated
{
    if (_isFindPushHere) {
        self.tabBarController.tabBar.hidden = YES;
        _navc = (IGCustomNavigationController *)self.navigationController;
        UIView *searchBar = (UIView *)[_navc.bgView viewWithTag:1000];
        searchBar.hidden = YES;
        _navc.iconButton.hidden = YES;
        _returnButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _returnButton.frame = CGRectMake(10, 10, 50, 25);
        [_returnButton setTitle:@"返回" forState:(UIControlStateNormal)];
        [_returnButton setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
        [_returnButton addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [_navc.bgView addSubview:_returnButton];
    }
}

- (void)buttonClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (_isFindPushHere) {
        self.tabBarController.tabBar.hidden = NO;
        _navc.iconButton.hidden = YES;
        [_returnButton removeFromSuperview];
    }
}


- (void)requestPlayDetailData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/VideoDetail?vid=%@",_vid];
    [IGAFNetworking requestWithUrlString:urlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        _dataDic = dataDic[@"data"];
      //[self avPlayerWithUrlStr:_dataDic[@"player_url"]];

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_dataDic[@"player_url"]]];
        [_webView loadRequest:request];
        [self setUpDataForHeadView];
        [MMProgressHUD dismissWithSuccess:@"加载完成" title:nil afterDelay:1];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
    
    NSString *moreVidioUrlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/get_related_videos_list?match_id=-1&video_id=%@",_vid];
    [IGAFNetworking requestWithUrlString:moreVidioUrlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        // 可以共用主页面的model,只得到vid 和 title俩个属性
        for (NSDictionary *dic in dataDic[@"data"]) {
            IGFindMainTBVModel *model = [[IGFindMainTBVModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_moreMovieArray addObject:model];
        }
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
}

// 请求评论的数据
- (void)requestCommentData
{
    NSString *commentUrlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getVideoComment?num=10&start=0&uid=348431&video_id=%@",_vid];
    [IGAFNetworking requestWithUrlString:commentUrlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        
        [_commentArray removeAllObjects];
        if ([dataDic[@"message"] isEqualToString:@"失败"]) {
            return ;
        }
        for (NSDictionary *dic in dataDic[@"data"][@"comment"]) {
            IGFindCommentModel *model = [[IGFindCommentModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_commentArray addObject:model];
        }
        _commentView.commentCountButton.userInteractionEnabled = YES;
        _commentView.commentIconButton.userInteractionEnabled = YES;
        
        [_commentView.commentCountButton setTitle:[NSString stringWithFormat:@"%ld",_commentArray.count] forState:(UIControlStateNormal)];
        [_commentView.commentIconButton setBackgroundImage:[UIImage imageNamed:@"iconfont-duihuaqipao3"] forState:(UIControlStateNormal)];
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

// 给tableViewHeadView赋值
- (void)setUpDataForHeadView
{
    _headView.titleLabel.text = _dataDic[@"title"];
    _headView.contentLabel.text = _dataDic[@"desc"];
    CGFloat height = [self customHeight:_dataDic[@"desc"] FontOfSize:15 width:kScreenWidth - 50];
    _headView.frame = CGRectMake(0, 0, 0, height + 85);
    [_headView sizeToFit];
    [_headView.backView sizeToFit];
    _tableView.tableHeaderView = _headView;
    
}


#pragma mark  --- UITableView的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _moreMovieArray.count;
    }
    return _commentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        IGFindRadioPlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IGFindRadioPlayTableViewCell" forIndexPath:indexPath];
        IGFindMainTBVModel *model = _moreMovieArray[indexPath.row];
        cell.titleLabel.text = model.title;
        return cell;
    }else{
        IGRadioPlayCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IGRadioPlayCommentTableViewCell" forIndexPath:indexPath];
        _tableView.separatorColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        IGFindCommentModel *model = _commentArray[indexPath.row];
        cell.model = model;
        if ([[IG_UserMessage shareUserMessage].dic[@"uid"] isEqualToString:model.uid]) {
            cell.deleteButton.hidden = NO;
            cell.deleteButton.tag = indexPath.row + 2000;
            [cell.deleteButton addTarget:self action:@selector(deleteButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 70;
    }else{
        return UITableViewAutomaticDimension;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        IGFindRadioPlayViewController *playVC = [[IGFindRadioPlayViewController alloc] init];
        IGFindMainTBVModel *model = _moreMovieArray[indexPath.row];
        playVC.vid = model.vid;
        playVC.isFindPushHere = YES;
        [self.navigationController pushViewController:playVC animated:YES];
    }else{
        NSLog(@"你要举报我??");
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 20)];
    if (section == 0) {
        label.backgroundColor = [UIColor grayColor];
        label.text = @"相关视频";
        label.textAlignment = NSTextAlignmentCenter;
        return label;
    }
    if (_commentArray.count != 0) {
        label.backgroundColor = [UIColor grayColor];
        label.text = [NSString stringWithFormat:@"评论 (%lu)",(unsigned long)_commentArray.count];
        return label;
    }else{
        _commentView.commentCountButton.userInteractionEnabled = NO;
        _commentView.commentIconButton.userInteractionEnabled = NO;
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 25;
    } else {
        if (_commentArray.count == 0) {
            return 1;
        }
        return 25;
    }
}

- (void)deleteButtonClick:(UIButton *)sender
{

    IGFindCommentModel *model = _commentArray[sender.tag - 2000];
    NSString *urlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/delVideoComment?id=%@",model.commentID];
    [IGAFNetworking requestWithUrlString:urlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSLog(@"%@",dataDic[@"message"]);
        [_commentArray removeObject:model];
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

// 添加评论的view
- (void)addCommmentView
{
    _commentView = [[IGFindCommentView alloc] initWithFrame:CGRectMake(0, kScreenHeight-44, kScreenWidth, 44)];
    _commentView.writeCommentView.backgroundColor = _headView.backgroundColor;
    [self.view addSubview:_commentView];
    
    [_commentView.cancerButton addTarget:self action:@selector(cancerButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_commentView.sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_commentView.commentIconButton addTarget:self action:@selector(commentCountAndIconButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_commentView.commentCountButton addTarget:self action:@selector(commentCountAndIconButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _commentView.commentTextFiled.delegate = self;
}

#pragma mark  -- UITextFiled代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (![IG_UserMessage shareUserMessage].isLoading) {
        [_commentView.commentTextFiled resignFirstResponder];
        IGLoginViewController *loginVC = [[IGLoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:^{
            [_tableView reloadData];
        }];
    }else{
    [self performSelector:@selector(resignTFFirstResponder) withObject:nil afterDelay:.9];
    }
}

- (void)resignTFFirstResponder
{
    [_commentView.commentTextFiled resignFirstResponder];
    [_commentView.writeCommentTV becomeFirstResponder];
}

- (void)cancerButtonAction:(UIButton *)sender
{
    [_commentView endEditing:YES];
    [self.view endEditing:YES];
}

- (void)sendButtonAction:(UIButton *)sender
{
    [_commentView endEditing:YES];
    [self.view endEditing:YES];
   NSDictionary *userDic = [IG_UserMessage shareUserMessage].dic;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"city"] = [[[IGMap shareLocationCityName] cityName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    dic[@"content"] = [_commentView.writeCommentTV.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    dic[@"uid"] = userDic[@"uid"];
    dic[@"video_id"] = _vid;
    [IGAFNetworking newRequestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/addVideoComment" parDic:dic method:POST finish:^(NSDictionary *dataDic) {
        NSLog(@"%@",dataDic[@"message"]);
        [self requestCommentData];
    } error:^(NSError *requestError) {
        NSLog(@"评论失败");
    }];
    _commentView.commentTextFiled.text = @"";
    _commentView.writeCommentTV.text = @"";
}


- (void)commentCountAndIconButtonAction:(UIButton *)sender
{
    CGPoint pointTemp =  _tableView.contentOffset;
    if (_ss) {
        if (_commentArray.count <= 2) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_commentArray.count - 1 inSection:1];
            [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }else{
            pointTemp.y = 235 + _headView.frame.size.height;
            [UIView animateWithDuration:.3 animations:^{
                _tableView.contentOffset = pointTemp;
            }];
        }
    
    }else {
        pointTemp.y = 0;
        [UIView animateWithDuration:.3 animations:^{
            _tableView.contentOffset = pointTemp;
        }];
    }
    _ss = !_ss;
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    NSLog(@"/.....%f",_headView.frame.size.height);
//    NSLog(@"%f",_tableView.contentOffset.y);
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
